package com.ujoin.util;

import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.digest.*;

// 说明：
// 1. 加密时调用setPassword，返回加密后String
// 2. 验证密码时调用isCorrect，传入用户输入的密码和数据库中加密后密码，函数返回true/false
public class HashPassword {
	private static final String pwdAlgorithm = "MD5";
	
	private static final String salt = "helloPwdCracker";
	
	public static String digestString(String password, String alg)
		throws NoSuchAlgorithmException {
		String newPassword;
		if (alg==null || alg.equals("MD5")) {
			newPassword = DigestUtils.md5Hex(password);
		}
		else if (alg.equals("SHA-256")) {
			newPassword = DigestUtils.sha256Hex(password);
		}
		else if (alg.equals("SHA-512")) {
			newPassword = DigestUtils.sha512Hex(password);
		}
		else if (alg.equals("NONE")) {
			newPassword = password;
		}
		else {
			newPassword = DigestUtils.shaHex(password);
		}
		return newPassword;
	}
	
	public static String encodePassword(String newPassword) {
		
		try {
			if (newPassword!=null && !newPassword.equals("")) {
				return digestString(salt + newPassword, pwdAlgorithm);
			}
			else return null;
		} catch (NoSuchAlgorithmException e) {
			// TODO: handle exception
			throw new RuntimeException("Security ERROR:" + e);
		}
	}
	
	public static boolean isCorrect(String inputPwd, String pwd) {
		if(inputPwd!=null && !"".equals(inputPwd)) {
			String password = encodePassword(inputPwd);
			return pwd.equals(password);
		}
		else return false;
	}
}
